import os
import configparser
from .service_core import OprationServiceApi
from .ingress_core import OprationIngressApi
from .deployment_core import OprationDeploymentApi
from deploy.models import deployInfo


class Create_Update_Application():
    '''在发布应用时调用此类对应用在集群中进行创建和更新'''

    def entrance(self, tag, port, namespace, application_name):
        '''判断应用是否存在并进行操作'''

        deployment_obj = OprationDeploymentApi(port, tag, namespace, application_name)
        service_obj = OprationServiceApi(namespace=namespace, service_name=application_name)
        ingress_obj = OprationIngressApi(namespace=namespace, ingress_name=application_name)
        service_names = service_obj.get_service_name_api()
        ingress_names = ingress_obj.get_ingress_name_api()
        deployment_names = deployment_obj.get_deployment_name_api()

        # deployment
        if application_name in deployment_names:
            deployment_obj.update_deployment_api()
        else:
            deployment_obj.create_deployment_api()
        # service
        if application_name not in service_names:
            service_obj.create_service_api(port)
        # ingress
        if application_name not in ingress_names:
            print("----------------------------------------------------\n")
            application = deployInfo.objects.filter(env=namespace, name=application_name, port=port).values().first()
            print(application)
            domain = application.get("domain")
            print("domain", domain, len(domain))
            if len(domain) > 0 and domain is not None:
                ingress_obj.create_ingress_api(application_name, port, domain)